//
//  TryHoneDataHelper.m
//  TryHone
//
//  Created by TryHone on 17/5/25.
//  Copyright © 2017年 TryHone. All rights reserved.
//

#import "JFDataHelper.h"
#import "JFStringHelper.h"
#import <objc/runtime.h>

@implementation JFDataHelper
/**
 *  NSString* 转 NSData*
 *
 *  @param string NSString*
 *
 *  @return NSData*
 */
+(NSData *)stringToData:(NSString *)string
{
    return [string dataUsingEncoding:NSUTF8StringEncoding];
}

/**
 *  NSData* 转 NSString*
 *
 *  @param data NSData*
 *
 *  @return NSString*
 */
+(NSString *)dataToString:(NSData *)data
{
    if (data && data.length > 0)
    {
        return [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    }
    return @"";
}

/**
 *  NSString* 转 char *
 *
 *  @param string NSString*
 *
 *  @return char*
 */
+(const char *)stringToChars:(NSString *)string
{
    if ([JFStringHelper isEmpty:string])
    {
        string = @"";
    }
    return [string UTF8String];
}

/**
 *  char* 转 NSString*
 *
 *  @param chars char*
 *
 *  @return NSString
 */
+(NSString *)charsToString:(char *)chars
{
    if (chars && strlen(chars) > 0)
    {
        return [NSString stringWithUTF8String:chars];
    }
    return @"";
}

/**
 *  NSData* 转 char*
 *
 *  @param data NSData*
 *
 *  @return char*
 */
+(char *)dataToChars:(NSData *)data
{
    if (data && data.length > 0)
    {
        return (char *)[data bytes];
    }
    return (char *)[[NSData data] bytes];
}

/**
 *  char* 转 NSData*
 *
 *  @param chars char*
 *
 *  @return NSData*
 */
+(NSData *)charsToData:(char *)chars
{
    if (chars && strlen(chars) > 0)
    {
        return [NSData dataWithBytes:chars length:strlen(chars)];
    }
    return [NSData data];
}


/**
 *  json转数据字典
 *
 *  @param json json字符串
 *
 *  @return 数据字典
 */
+(NSDictionary *)jsonToDictionary:(NSString *)json
{
    NSObject *obj = [JFDataHelper jsonToObject:json];
    if ([obj isKindOfClass:[NSDictionary class]])
    {
        return (NSDictionary *)obj;
    }
    return nil;
}

/**
 *  json转对象
 *
 *  @param json json字符串
 *
 *  @return 对象
 */
+(NSObject *)jsonToObject:(NSString *)json
{
    if ([JFStringHelper isNotEmpty:json])
    {
        NSData * data = [json dataUsingEncoding:NSUTF8StringEncoding];
        NSError *parseError = nil;
        NSObject *obj = (NSObject *)[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&parseError];
        if (parseError)
        {
            NSLog(@"json转对象失败!%@",parseError);
            return nil;
        }
        return obj;
    }
    return nil;
}

/**
 *
 *  json转数组
 *
 *  @param json json字符串
 *
 *  @return 数组
 */
+(NSArray *)jsonTOArray:(NSString *)json
{
    NSObject *obj = [JFDataHelper jsonToObject:json];
    if ([obj isKindOfClass:[NSArray class]])
    {
        return (NSArray *)obj;
    }
    return nil;
}

/**
 *  数据字典转json
 *
 *  @param dic 数据字典
 *
 *  @return json字符串
 */
+(NSString *)dictionaryToJson:(NSDictionary *)dic
{
    if (dic && dic.count > 0)
    {
        return [JFDataHelper objectToJson:dic];
    }
    return @"";
}

/**
 *
 *  对象转json
 *
 *  @param obj 对象
 *
 *  @return json字符串
 */
+(NSString *)objectToJson:(NSObject *)obj
{
    if (obj)
    {
        NSError *parseError = nil;
        NSData *data = [NSJSONSerialization dataWithJSONObject:obj options:NSJSONWritingPrettyPrinted error:&parseError];
        if (parseError)
        {
            NSLog(@"对象转json格式失败!%@",parseError);
            return @"";
        }
        return [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    }
    return @"";
}

/**
 *
 *  数组转json
 *
 *  @param jsonArray 数据字典数组
 *
 *  @return json字符串
 */
+(NSString *)arrayToJson:(NSArray *)jsonArray
{
    if (jsonArray && jsonArray.count > 0)
    {
        return [JFDataHelper objectToJson:jsonArray];
    }
    return @"";
}

/**
 * 复制数据字典到另外一个数据字典
 *
 *  @param srcDic  源数据字典
 *  @param destDic 目标数据字典
 *  @param flag    是否强复制，NO:只有替换的字段的值不为空，才替换，否则保留原来的值 YES:全部复制替换
 */
+(void) copyDictionay:(NSDictionary *)srcDic toDictionary:(NSMutableDictionary *)destDic isStrong:(BOOL)flag
{
    if (srcDic && destDic)
    {
        for (NSString *key in [srcDic allKeys])
        {
            NSString *temp = [srcDic objectForKey:key];
            if (flag)
            {
                [destDic setObject:temp forKey:key];
            }
            else
            {
                if ([JFStringHelper isNotEmpty:temp])
                {
                    [destDic setObject:temp forKey:key];
                }
            }
        }
    }
}

/**
 *  数据字典转字符串
 *
 *  @param dic    要转换的数据字典
 *  @param split0 第一层分割符号   ,
 *  @param split1 第二层分隔符    =
 *
 *  @return 转换后的字符串 name=liubao,age=20,lover=xiaozhu
 */
+(NSString *)dictionayToString:(NSDictionary *)dic firstSplit:(NSString *)split0 secondSplit:(NSString *)split1
{
    NSMutableArray *result = [NSMutableArray array];
    if(dic != nil && dic != NULL)
    {
        for(NSString *key in [dic allKeys])
        {
            NSString *value = [dic objectForKey:key];
            if([JFStringHelper isEmpty:value])
            {
                value = @"";
            }
            [result addObject:[[key stringByAppendingString:split1]stringByAppendingString:value]];
        }
    }
    return [result componentsJoinedByString:split0];
}

/**
 *  字符串转成对象
 *
 *  @param str    要转换的字符串 例如name=liubao,age=20,lover=xiaozhu
 *  @param split0 第一层分割符号  ,
 *  @param split1 第二层分隔符    =
 *
 *  @return 转换后的数据字典
 */
+(NSDictionary *)stringToDictionay:(NSString *)str firstSplit:(NSString *)split0 secondSplit:(NSString *)split1
{
    NSMutableDictionary *result = [NSMutableDictionary dictionary];
    if ([JFStringHelper isNotEmpty:str] && [JFStringHelper isNotEmpty:split0] && [JFStringHelper isNotEmpty:split1])
    {
        NSArray *first = [JFStringHelper string:str splitWith:split0];
        if (first && first.count > 0)
        {
            for (NSString *temp in first)
            {
                NSArray *second = [JFStringHelper string:temp splitWith:split1];
                if (second && second.count == 2)
                {
                    [result setObject:[second objectAtIndex:1] forKey:[second objectAtIndex:0]];
                }
            }
        }
    }
    return result;
}

/**
 *  对象转成数据字典
 *
 *  @param obj 对象
 *
 *  @return 数据字典
 */
+(NSDictionary *)objectToDictionary:(NSObject *)obj
{
    if (obj)
    {
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        unsigned int propsCount;
        objc_property_t *props = class_copyPropertyList([obj class], &propsCount);
        for(int i = 0;i < propsCount; i ++)
        {
            objc_property_t prop = props[i];
            NSString *propName = [NSString stringWithUTF8String:property_getName(prop)];
            id value = [obj valueForKey:propName];
            if(value == nil)
            {
                value = [NSNull null];
            }
            else
            {
                value = [JFDataHelper getObjectInternal:value];
            }
            [dic setObject:value forKey:propName];
        }
        free(props);
        return dic;
    }
    return nil;
}

/**
 *  获取objc对象
 *
 *  @param obj id对象
 *
 *  @return objc对象
 */
+ (id)getObjectInternal:(id)obj
{
    if (obj)
    {
        if([obj isKindOfClass:[NSString class]] || [obj isKindOfClass:[NSNumber class]] || [obj isKindOfClass:[NSNull class]])
        {
            return obj;
        }
        if([obj isKindOfClass:[NSArray class]])
        {
            NSArray *objarr = obj;
            NSMutableArray *arr = [NSMutableArray arrayWithCapacity:objarr.count];
            for(int i = 0;i < objarr.count; i ++)
            {
                [arr setObject:[JFDataHelper getObjectInternal:[objarr objectAtIndex:i]] atIndexedSubscript:i];
            }
            return arr;
        }
        
        if([obj isKindOfClass:[NSDictionary class]])
        {
            NSDictionary *objdic = obj;
            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:[objdic count]];
            for(NSString *key in objdic.allKeys)
            {
                [dic setObject:[JFDataHelper getObjectInternal:[objdic objectForKey:key]] forKey:key];
            }
            return dic;
        }
        return [JFDataHelper objectToDictionary:obj];
    }
    return [NSNull null];
}

/**
 *  数据字典转成对象
 *
 *  @param srcDic  数据字典
 *  @param destObj 目标对象
 */
+(void)dictionary:(NSDictionary *)srcDic ToObject:(NSObject *)destObj
{
    unsigned int outCount, i;
    Class c = [destObj class];
    objc_property_t *properties = class_copyPropertyList(c, &outCount);
    for (i = 0; i < outCount; i ++)
    {
        objc_property_t property = properties[i];
        NSString *propertyName = [NSString stringWithUTF8String:property_getName(property)];
        NSString *propertyType = [NSString stringWithUTF8String:property_getAttributes(property)];
        if ([[srcDic allKeys] containsObject:propertyName])
        {
            id value = [srcDic valueForKey:propertyName];
            if (![value isKindOfClass:[NSNull class]] && value != nil)
            {
                if ([value isKindOfClass:[NSDictionary class]])
                {
                    NSString *className = [JFDataHelper getClassNameFromObjectAttrType:propertyType];
                    id pro = [JFDataHelper getClassInstanceByName:className];
                    [JFDataHelper dictionary:value ToObject:pro];
                    [destObj setValue:pro forKey:propertyName];
                }
                else
                {
                    [destObj setValue:value forKey:propertyName];
                }
            }
        }
    }
    free(properties);
}

/**
 *  根据对象的属性类型获取类名
 *
 *  @param attrType 属性
 *
 *  @return 类名
 */
+(NSString *)getClassNameFromObjectAttrType:(NSString *)attrType
{
    NSString *str = [JFStringHelper firstSubStringWith:attrType byRegExp:@"\"\\w+\""];
    if (str && str.length > 2)
    {
        str = [JFStringHelper subStringWith:str fromIndex:1 count:(str.length - 1)];
    }
    return str;
}
/**
 *  根据类名得到类的实例
 *
 *  @param className 类名
 *
 *  @return 实例
 */
+(id) getClassInstanceByName: (NSString *)className
{
    Class aClass = NSClassFromString(className);
    if (aClass)
    {
        id anInstance = [[aClass alloc] init];
        return anInstance;
    }
    return nil;
}
/**
 *
 *  位转字节
 *
 *  @param bits 位数组
 *
 *  @return 字节
 */
+(Byte)bitsToByte:(NSArray *)bits
{
    Byte byte = 0;
    NSInteger count = bits.count - 1;
    for (NSInteger i = count; i >= 0; i --)
    {
        NSNumber *value = bits[i];
        byte |= (value.intValue) << count - i;
    }
    return byte;
}

/**
 *
 *  字节转位数组
 *
 *  @param byte 字节
 *
 *  @return 位数组
 */
+(NSArray *)byteToBits:(Byte)byte
{
    NSMutableArray *bits = [NSMutableArray arrayWithCapacity:8];
    for(int i = 7; i >= 0; i --)
    {
        if(byte & (1 << i))
        {
            [bits addObject:@1];
        }
        else
        {
            [bits addObject:@0];
        }
    }
    return bits;
}
@end
